#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import base64

from Ump import utils
from Ump.common import log
from Ump.objs.db import models
from Ump.common import exception
from Ump.objs.session_wrapper import enable_log_and_session, _sw
from Ump.objs.manager_base import Manager

from Ump.common.mail import Mail


LOG = log.get_log('Ump.objs.customer.manager')


@models.add_model(models.Mail)
class MailManager(Manager):

    def __init__(self):
        super(MailManager, self).__init__()

    @enable_log_and_session(resource='mail', event='setting')
    def create(self, _logger, params):
        mail = params.get('mail')
        password = params.get('password')
        server = params.get('server')
        port = params.get('port')
        use_smtp = params.get('use_smtp')
        protocol = params.get('protocol')

        _logger.set_obj(mail)

        mail_sql = _sw.get_one(model=models.Mail, id_or_spec={})
        if mail_sql: 
            params['id'] = mail_sql.id
            return self._update(params)

        if _sw.get_list(model=models.Mail):
            raise exception.MailFound

        _logger.update_props(oplog_obj=mail)

        values = {
            'mail': mail,
            'password': base64.b64encode(password),
            'server': server,
            'port': port,
            'use_smtp': use_smtp,
            'protocol': protocol
        }

        mail = models.Mail(values).save()
        return mail

    @enable_log_and_session(resource='mail', event='delete')
    def delete(self, _logger, params):
        mail_id = params['id']

        mail = _sw.get_one(model=models.Mail, id_or_spec=mail_id)
        if not mail:
            raise exception.MailNotFound(mail_id=mail_id)

        _logger.set_obj(mail.mail)

        return mail.delete()

    # @enable_log_and_session(resource='mail', event='update', disable_oplog=True)
    # def update(self, _logger, params):
    #     return _update(params)

    def _update(self, params):
        mail_id = params.get('id')
        mail = params.get('mail')
        password = params.get('password')
        server = params.get('server')
        port = params.get('port')
        use_smtp = params.get('use_smtp')
        protocol = params.get('protocol')

        mail_sql = _sw.get_one(model=models.Mail, id_or_spec=mail_id)
        if not mail_sql:
            raise exception.MailNotFound(mail_id=mail_id)
        # Encryption password
        values = {}
        utils.update_values(values, 'mail', mail)
        # aim to here
        utils.update_values(values, 'password', base64.b64encode(password))
        utils.update_values(values, 'server', server)
        utils.update_values(values, 'port', port)
        utils.update_values(values, 'use_smtp', use_smtp)
        utils.update_values(values, 'protocol', protocol)
        # update show  you can see the passwod of encryptioned
        mail_sql.update(values)
        return mail_sql

    @enable_log_and_session(resource='mail', event='send')
    def test(self, _logger, params):
        mail_addr = params.get('mail')
        password = params.get('password')
        server = params.get('server')
        port = params.get('port')
        use_smtp = params.get('use_smtp')
        protocol = params.get('protocol')

        _logger.set_obj(mail_addr)

        subject = '这是一封测试邮件!'
        msg = '收到此邮件表明你在邮件配置中邮件发件人可正常发送及接受邮件！'

        mail = Mail(mail_addr, password)
        mail.mail_server = server
        if protocol == 'SSL':
            mail.use_ssl = True

        mail.mail_port = int(port)
        rec_list = _sw.get_one(model=models.SysconfigForUMP, id_or_spec={'name':'mail_receive.list'})
        if rec_list:
            mail.to_addrs = [ x for x in str(rec_list.value_setting).split(';') if x.strip()]

        mail.to_addrs += [mail_addr]

        res = mail.sendmail(subject, msg)

@models.add_model(models.Customer)
class CustomerManager(Manager):

    def __init__(self):
        super(CustomerManager, self).__init__()

    @enable_log_and_session(resource='customer', event='setting')
    def create(self, _logger, params):
        company = params['company']
        name = params.get('name')
        contact = params['contact']
        address = params['address']
        telephone = params['telephone']
        callhome = params.get('callhome')
        callhome = callhome in ['true', True]
        params['callhome'] = callhome

        _logger.set_obj(company)

        customer = _sw.get_one(model=models.Customer, id_or_spec={})
        if customer: 
            params['id'] = customer.id
            return self._update(params)

        if _sw.get_list(model=models.Customer):
            raise exception.CustomerFound

        _logger.update_props(oplog_obj=company)

        customer = models.Customer(params).save()
        return customer 

    def _update(self, params):
        customer_id = params.get('id')
        company = params['company']
        name = params.get('name')
        contact = params['contact']
        address = params['address']
        telephone = params['telephone']
        callhome = params.get('callhome')
        callhome = callhome in ['true', True]
        params['callhome'] = callhome

        mail_sql = _sw.get_one(model=models.Customer, id_or_spec=customer_id)
        if not mail_sql:
            raise exception.CustomerNotFound(customer_id=customer_id)

#        _logger.set_obj(mail.mail)

        values = {}
        utils.update_values(values, 'company', company)
        utils.update_values(values, 'name', name)
        utils.update_values(values, 'contact', contact)
        utils.update_values(values, 'address', address)
        utils.update_values(values, 'telephone', telephone)
        utils.update_values(values, 'callhome', callhome)

        mail_sql.update(values)
        return mail_sql

    @enable_log_and_session(resource='customer', event='delete')
    def delete(self, _logger, params):
        customer_id = params['id']

        customer_name = _sw.get_one(model=models.Customer, id_or_spec=customer_id)
        if not customer_name:
            raise exception.MailNotFound(customer_id=customer_id)

        _logger.set_obj(customer_name.company)
        return customer_name.delete()
